package com.idrive.activity;

import java.util.UUID;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.idrive.R;
import com.idrive.database.dao.LocationDataDao;
import com.idrive.database.dto.LocationData;
import com.idrive.service.PathTrackerService;

public class PathTrackerActivity extends Activity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_path_tracker);

		ToggleButton activateToggleButton = (ToggleButton) findViewById(R.id.activateToggleButton);

		if (isPathTrackerRunning()) {
			activateToggleButton.toggle();
		}

		activateToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
				try {
					if (isPathTrackerRunning()) {
						stopService(new Intent(PathTrackerActivity.this, PathTrackerService.class));
					} else {
						final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

						if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
							displayAlertDialog();
						} else {
							LocationData.LOCATION_UUID = UUID.randomUUID().toString();
							startService(new Intent(PathTrackerActivity.this, PathTrackerService.class));
						}

					}

				} catch (Exception exception) {
					exception.printStackTrace();
					Toast.makeText(PathTrackerActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		});

		final Button button = (Button) findViewById(R.id.viewPathButton);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				Intent myIntent = new Intent(PathTrackerActivity.this, PathTrackerViewActivity.class);
				PathTrackerActivity.this.startActivity(myIntent);
			}
		});

		final Button clearButton = (Button) findViewById(R.id.clearHistoryButton);
		clearButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				final AlertDialog.Builder builder = new AlertDialog.Builder(PathTrackerActivity.this);
				builder.setMessage("Are you sure do you want to clear Path Tracker history?").setCancelable(false)
				        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					        public void onClick(final DialogInterface dialog, final int id) {
					        	LocationDataDao dao = new LocationDataDao(getBaseContext());
					    		dao.clear();
					        }
				        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
					        public void onClick(final DialogInterface dialog, final int id) {
						        dialog.cancel();
					        }
				        });
				final AlertDialog alert = builder.create();
				alert.show();
			}
		});
	}

	private void displayAlertDialog() {

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("GPS seems to be disabled, do you want to enable it?").setCancelable(false)
		        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			        public void onClick(final DialogInterface dialog, final int id) {
				        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
				        turnGPSOn();
				        LocationData.LOCATION_UUID = UUID.randomUUID().toString();
				        startService(new Intent(PathTrackerActivity.this, PathTrackerService.class));
			        }
		        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
			        public void onClick(final DialogInterface dialog, final int id) {
				        dialog.cancel();
			        }
		        });
		final AlertDialog alert = builder.create();
		alert.show();

	}

	private void turnGPSOn() {
		String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (!provider.contains("gps")) { // if gps is disabled
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}

	private boolean isPathTrackerRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.idrive.service.PathTrackerService".equals(service.service.getClassName())) {
				return Boolean.TRUE;
			}
		}
		return Boolean.FALSE;
	}
}
